// pages/ciema/ciema.js
const app = getApp();
Page({
  data: {
    isnull:false,
    index: 0,
    list: [],
    option1: [{
        text: '深圳',
        value: 0
      },
      {
        text: '北京',
        value: 1
      },
      {
        text: '广州',
        value: 2
      },
      {
        text: '上海',
        value: 3
      },
    ],
    userLocationList: {},
    value1: 0,
    location:[],
    currPage:1,
  },
  onLoad() {
    this.getLocation()
  },
  getList() {
    app.get('cinema/list?cityName='+this.data.option1[this.data.index].text+'&&currPage='+this.data.currPage).then(res => {
      if(res.data.length===0){
         this.setData({
          isnull:true
         })
      }
      let cinemaList=res.data||[];
       cinemaList=cinemaList.map(item => {
        // 计算两个坐标之间的距离
        let lat1, lng1, lat2, lng2;
        lat1 = item.latitude;
        lng1 = item.longitude;
        lat2 = this.data.location.latitude;
        lng2 = this.data.location.longitude;
        let distance = this.getDistance(lat1, lng1, lat2, lng2);
        distance = distance.toFixed(2) + 'km';
        return {
          ...item,
          distance: distance || '距离未知'
        }
      })
      this.setData({
        list:[
          ...this.data.list,
          ...cinemaList
        ]
      });
    })
  },
  change(ev) {
    let detail = ev.detail
    this.setData({
      index: detail,
      list:[]
    })
    this.getList()
  },
  getLocation() {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        // res里面包含了经纬度
        let {
          latitude,
          longitude
        } = res;
        this.setData({
          location: {
            latitude,
            longitude
          }
        })
        this.getList(res);
      },
      fail: (err) => {
        this.setData({
          city: '定位失败,请手动选择'
        })
      }
    })
  },
  getDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = lat1 * Math.PI / 180.0;
    var radLat2 = lat2 * Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    return s;
  },
  onReachBottom(){
     this.setData({
      currPage:this.data.currPage+1
     })
     this.getList()
  }
})